package com.huw.debuger;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.content.Context;

import com.light.roller.Roller;
public class FileIO{
  
	
	public static enum FileName
	{
		OpenNum,
		CurrentNum,
		ButtonSize,
		Volume
	}
	
    static public void SaveGame(BaseGameActivity m_game,int StageNum) 
    {
    	SaveOpenNum(m_game,StageNum);
    	SaveCurrentNum(m_game,StageNum);	
    }
    

    
    static private void SaveCammand(BaseGameActivity m_game,int Num,FileName type)
    {
    	FileOutputStream fos = null;        		
		
		try 
		{
			fos = m_game.openFileOutput("GTrecord"+type,Context.MODE_WORLD_WRITEABLE);
			fos.write(String.valueOf(Num).getBytes("utf-8"));
			fos.close();
		} 
		catch (Exception e) { e.printStackTrace(); }
		finally
		{
			try 
			{
				if(fos != null)
				{
					fos.flush();
					fos.close();
				}
			} 
			catch (Exception e2) 
			{
				e2.printStackTrace();
			}
		}     
    }
    
    static private void SaveCurrentNum(BaseGameActivity m_game,int StageNum)
    {    		    		
    	SaveCammand(m_game,StageNum,FileName.CurrentNum);  
    }
    
    static private void SaveOpenNum(BaseGameActivity m_game,int StageNum)
    {
    	if(StageNum>=LoadGame(m_game,FileName.OpenNum))
    	{
    		SaveCammand(m_game,StageNum,FileName.OpenNum);  
    	}      
    }
    
    static public void SaveVolume(BaseGameActivity m_game, int volume)
    {
    	SaveCammand(m_game, volume, FileName.Volume);  
    }
    
    static public void SaveButtonSize(BaseGameActivity m_game,int size) 
    {
    	SaveCammand(m_game,size,FileName.ButtonSize);     
    }

    static public int LoadGame(BaseGameActivity m_game,FileName num)
    {
      
    	if(Debugger.UNLOCK_ALL_STAGE&&num==FileName.OpenNum)return Roller.StageNum;
    	
    	FileInputStream fin = null;
        String data = null;
        try {
        fin = m_game.openFileInput("GTrecord"+num);
         byte[] reader = new byte[fin.available()];
         while(fin.read(reader) != -1);
         data = new String(reader);
         
         fin.close();
        } catch (Exception e) {
        	if(num == FileName.ButtonSize)return 2;
        	return 1;        	
        	
 	 }
        finally
 	 {
 		 try {
 			 if(fin != null){
 				 fin.close();
 			 }
 		 } catch (Exception e2) {
 			 e2.printStackTrace();
 		 } 		 
 	 } 
 	 
 	int intValue = Integer.valueOf(data);
 	if(intValue>Roller.StageNum)intValue = Roller.StageNum;
 	return intValue; 
    }
}